package com.jgp.sys.utils;

import com.getui.push.v2.sdk.ApiHelper;
import com.getui.push.v2.sdk.GtApiConfiguration;
import com.getui.push.v2.sdk.api.PushApi;
import com.getui.push.v2.sdk.api.StatisticApi;
import com.getui.push.v2.sdk.api.UserApi;
import com.getui.push.v2.sdk.common.ApiResult;
import com.getui.push.v2.sdk.dto.CommonEnum;
import com.getui.push.v2.sdk.dto.req.Audience;
import com.getui.push.v2.sdk.dto.req.AudienceDTO;
import com.getui.push.v2.sdk.dto.req.Settings;
import com.getui.push.v2.sdk.dto.req.Strategy;
import com.getui.push.v2.sdk.dto.req.message.PushChannel;
import com.getui.push.v2.sdk.dto.req.message.PushDTO;
import com.getui.push.v2.sdk.dto.req.message.PushMessage;
import com.getui.push.v2.sdk.dto.req.message.android.AndroidDTO;
import com.getui.push.v2.sdk.dto.req.message.android.GTNotification;
import com.getui.push.v2.sdk.dto.req.message.android.ThirdNotification;
import com.getui.push.v2.sdk.dto.req.message.android.Ups;
import com.getui.push.v2.sdk.dto.req.message.ios.Alert;
import com.getui.push.v2.sdk.dto.req.message.ios.Aps;
import com.getui.push.v2.sdk.dto.req.message.ios.IosDTO;
import com.getui.push.v2.sdk.dto.res.CidStatusDTO;
import com.getui.push.v2.sdk.dto.res.TaskIdDTO;
import com.jgp.common.utils.JGPUtil;
import lombok.extern.log4j.Log4j2;
import org.apache.commons.lang3.StringUtils;

import java.util.*;

/**
 * 项目   jgp-cloud-parent
 * 作者   loufei
 * 时间   2021/9/1
 */
@Log4j2
public class AppPushUtil {
    private PushApi pushApi;
    private StatisticApi statisticApi;
    private UserApi userApi;
    private Options options;

    public static void main(String[] args) {
        AppPushUtil.Options options = new AppPushUtil.Options("uni.UNIA7DF236", "t0FxfXbtYlAEtUguE6cjc1", "s2jTwzErXa7c0kAHJCDiP9",
                                                              "88mbEBZdrZ9QTlGQqMi8j4", "https://restapi.getui.com/v2/");
        /*options.setTtl();
        options.setAsync();
        options.setXmChannel();*/
        
        AppPushUtil pushUtil = AppPushUtil.build(options);
        
        List<String> cIds = new ArrayList<>();
        cIds.add("a3b4b865c109d2fec71004d08e1f75ad");
        
        Map<String, Object> params = new HashMap<>();
        params.put("a", "1");
        params.put("b", "2");
        
        //pushUtil.notice(cIds, "xxxx" + System.currentTimeMillis(), "xxxx", params);
        pushUtil.send(cIds,params,true);
    }

    public static AppPushUtil build(Options options) {
        if (StringUtils.isNotBlank(options.getMaxConnections())) {
            System.setProperty("http.maxConnections", options.getMaxConnections());
        } else {
            System.setProperty("http.maxConnections", "200");
        }
        
        AppPushUtil util = new AppPushUtil();
        util.options = options;
        GtApiConfiguration apiConfiguration = new GtApiConfiguration();
        apiConfiguration.setAppId(options.getAppId());
        apiConfiguration.setAppKey(options.getAppKey());
        apiConfiguration.setMasterSecret(options.getMasterSecret());
        apiConfiguration.setDomain(options.getDomain());
        apiConfiguration.setOpenCheckHealthDataSwitch(true);
        apiConfiguration.setSoTimeout(5000);
        apiConfiguration.setConnectTimeout(5000);
        //健康检测时间间隔
        apiConfiguration.setCheckHealthInterval(500);
        ApiHelper apiHelper = ApiHelper.build(apiConfiguration);
        util.pushApi = apiHelper.creatApi(PushApi.class);
        util.statisticApi = apiHelper.creatApi(StatisticApi.class);
        util.userApi = apiHelper.creatApi(UserApi.class);
        return util;
    }
    
    public ApiResult<Map<String, Map<String, String>>> send(List<String> clientIds,Map<String, Object> params,Boolean needNotice) {
        PushDTO<Audience> pushDTO = new PushDTO<>();
        // 设置推送参数
        pushDTO.setRequestId(System.currentTimeMillis() + "");
        
        if (Objects.isNull(params)) {
            params = new HashMap<>();
        }
        
        params.put("needNotice",needNotice);
        String payload = JGPUtil.toJson(params).replace("\n", "").replace("\t", "").replace(" ", "");
        
        Settings settings = new Settings();
        settings.setTtl(this.options.ttl);
        Strategy strategy = new Strategy();
        strategy.setSt(1);
        settings.setStrategy(strategy);
        pushDTO.setSettings(settings);
        
        PushMessage pushMessage = new PushMessage();
        pushMessage.setTransmission(payload);
        pushDTO.setPushMessage(pushMessage);
        
        ApiResult<TaskIdDTO> msg = pushApi.createMsg(pushDTO);
        String taskId = msg.getData().getTaskId();
        
        Audience audience = new Audience();
        clientIds.forEach(clientId -> audience.addCid(clientId));
        
        
        AudienceDTO audienceDTO = new AudienceDTO();
        audienceDTO.setTaskid(taskId);
        audienceDTO.setAsync(this.options.async);
        audienceDTO.setAudience(audience);
        
        ApiResult<Map<String, Map<String, String>>> apiResult = pushApi.pushListByCid(audienceDTO);
        if (apiResult.isSuccess()) {
            // success
            System.out.println(apiResult.getData());
        } else {
            // failed
            System.out.println("code:" + apiResult.getCode() + ", msg: " + apiResult.getMsg());
        }
        return apiResult;
    }
    
    public ApiResult<Map<String, Map<String, String>>> notice(List<String> clientIds, String title, String content, Map<String, Object> params) {
        PushDTO<Audience> pushDTO = new PushDTO<>();
        // 设置推送参数
        pushDTO.setRequestId(System.currentTimeMillis() + "");
        
        if (Objects.isNull(params)) {
            params = new HashMap<>();
        }
    
        params.put("title",title);
        params.put("content",content);
        String payload = JGPUtil.toJson(params).replace("\n", "").replace("\t", "").replace(" ", "");
        
        String intent = "intent:#Intent;action=android.intent.action.oppopush;launchFlags=0x14000000;component=" + this.options.pkgName + "/io.dcloud" +
                ".PandoraEntry;S.UP-OL-SU=true;S.title=" + title + ";S.content=" + content + ";S.payload=" + payload + ";end";
        
        Settings settings = new Settings();
        settings.setTtl(this.options.ttl);
        Strategy strategy = new Strategy();
        strategy.setSt(1);
        settings.setStrategy(strategy);
        pushDTO.setSettings(settings);
        
        // 个推
        PushMessage pushMessage = new PushMessage();
        GTNotification notification = new GTNotification();
        notification.setClickType(CommonEnum.ClickTypeEnum.TYPE_INTENT.type);
        notification.setIntent(intent);
        notification.setTitle(title);
        notification.setBody(content);
        notification.setBadgeAddNum("1");
        pushMessage.setNotification(notification);
        //pushMessage.setTransmission(payload);
        pushDTO.setPushMessage(pushMessage);
        
        // 三方通道
        PushChannel pushChannel = new PushChannel();
        
        //android
        AndroidDTO androidDTO = new AndroidDTO();
        ThirdNotification thirdNotification = new ThirdNotification();
        thirdNotification.setTitle(title);
        thirdNotification.setBody(content);
        thirdNotification.setClickType(CommonEnum.ClickTypeEnum.TYPE_INTENT.type);
        thirdNotification.setIntent(intent);
        
        Ups ups = new Ups();
        ups.setNotification(thirdNotification);
        ups.addOption("HW", "/message/android/notification/badge/class", "io.dcloud.PandoraEntry");
        ups.addOption("HW", "/message/android/notification/badge/add_num", 1);
        ups.addOption("HW", "/message/android/notification/importance", "HIGH");
        ups.addOption("HW", "/message/android/notification/default_sound", true);
        ups.addOption("VV", "classification", 1);
        androidDTO.setUps(ups);
        pushChannel.setAndroid(androidDTO);
        
        //ios
        Alert alert = new Alert();
        alert.setTitle(title);
        alert.setBody(content);
        Aps aps = new Aps();
        //1表示静默推送(无通知栏消息)，静默推送时不需要填写其他参数。
        //苹果建议1小时最多推送3条静默消息
        aps.setContentAvailable(0);
        aps.setSound("default");
        aps.setAlert(alert);
        IosDTO iosDTO = new IosDTO();
        iosDTO.setAps(aps);
        iosDTO.setType("notify");
        iosDTO.setAutoBadge("+1");
        pushChannel.setIos(iosDTO);
        
        
        pushDTO.setPushChannel(pushChannel);
        
        ApiResult<TaskIdDTO> msg = pushApi.createMsg(pushDTO);
        String taskId = msg.getData().getTaskId();
        
        Audience audience = new Audience();
        clientIds.forEach(clientId -> audience.addCid(clientId));
        
        
        AudienceDTO audienceDTO = new AudienceDTO();
        audienceDTO.setTaskid(taskId);
        audienceDTO.setAsync(this.options.async);
        audienceDTO.setAudience(audience);
        
        ApiResult<Map<String, Map<String, String>>> apiResult = pushApi.pushListByCid(audienceDTO);
        if (apiResult.isSuccess()) {
            // success
            System.out.println(apiResult.getData());
        } else {
            // failed
            System.out.println("code:" + apiResult.getCode() + ", msg: " + apiResult.getMsg());
        }
        return apiResult;
    }
    
    /**
     * 查询用户状态
     * @param cIds
     * @return
     */
    public ApiResult<Map<String, CidStatusDTO>> queryUserStatus(Set<String> cIds) {
        return userApi.queryUserStatus(cIds);
    }
    
    static class Options {
        private String pkgName;
        private String appId;
        private String appKey;
        private String masterSecret;
        private String domain;
        private String maxConnections;
        //超时时间  消息离线时间设置，单位毫秒，-1表示不设离线, -1 ～ 3 * 24 * 3600 * 1000之间
        private Integer ttl = 3600000;
        //异步
        private Boolean async = true;
        //厂商配置
        //小米后台申请的通知类别id
        private String xmChannel;
        
        public Options(String pkgName, String appId, String appKey, String masterSecret, String domain) {
            this.pkgName = pkgName;
            this.appId = appId;
            this.appKey = appKey;
            this.masterSecret = masterSecret;
            this.domain = domain;
        }
        
        public Options(String pkgName, String appId, String appKey, String masterSecret, String domain, String maxConnections) {
            this.pkgName = pkgName;
            this.appId = appId;
            this.appKey = appKey;
            this.masterSecret = masterSecret;
            this.domain = domain;
            this.maxConnections = maxConnections;
        }
        
        public String getPkgName() {
            return pkgName;
        }
        
        public String getAppId() {
            return appId;
        }
        
        public String getAppKey() {
            return appKey;
        }
        
        public String getMasterSecret() {
            return masterSecret;
        }
        
        public String getDomain() {
            return domain;
        }
        
        public String getMaxConnections() {
            return maxConnections;
        }
        
        public String getXmChannel() {
            return xmChannel;
        }
        
        public void setXmChannel(String xmChannel) {
            this.xmChannel = xmChannel;
        }
    
        public Boolean getAsync() {
            return async;
        }
    
        public void setAsync(Boolean async) {
            this.async = async;
        }
    
        public Integer getTtl() {
            return ttl;
        }
    
        public void setTtl(Integer ttl) {
            this.ttl = ttl;
        }
    }
    
}
